<?php
//default_sorting
if(!$_SESSION['images_sort']){
	$e=explode("|", $conf['images_sort']);
	$_SESSION['images_sortby']=string_template($e[0], array('lang'=>$_SESSION['lang_short']));
	$_SESSION['images_sort']=$e[1];
}
//

//funckja zmieniajaca rozdzielczosc obrazka
function ImageCopyResample(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $resample=NULL) {
	$pxls = intval($src_w / $dst_w)-1;
	if (($resample != "bicubic" && $pxls>=2) or $resample == "bilinear"){ //slow but better quality
		ImagePaletteCopy ($dst_img, $src_img);
		$rX = $src_w / $dst_w;
		$rY = $src_h / $dst_h;
		$nY = 0;
		for ($y=$src_y; $y<$dst_h; $y++) {
			$oY = $nY;
			$nY = intval(($y + 1) * $rY+.5);
			$nX = 0;
			for ($x=$src_x; $x<$dst_w; $x++) {
				$r = $g = $b = $a = 0;
				$oX = $nX;
				$nX = intval(($x + 1) * $rX+.5);
				$c = ImageColorsForIndex ($src_img, ImageColorAt ($src_img, $nX, $nY));
				$r += $c['red']; $g += $c['green']; $b += $c['blue']; $a++;
				$c = ImageColorsForIndex ($src_img, ImageColorAt ($src_img, $nX-$pxls, $nY-$pxls));
				$r += $c['red']; $g += $c['green']; $b += $c['blue']; $a++;
				//you can add more pixels here! eg "$nX, $nY-$pxls" or "$nX-$pxls, $nY"
				ImageSetPixel ($dst_img, ($x+$dst_x-$src_x), ($y+$dst_y-$src_y), ImageColorClosest ($dst_img, $r/$a, $g/$a, $b/$a));
			}
		}
		return true;
	}
	elseif ($resample=="bicubic") { //very slow but better quality
		ImagePaletteCopy ($dst_img, $src_img);
		$rX = $src_w / $dst_w;
		$rY = $src_h / $dst_h;
		$nY = 0;
		for ($y=$src_y; $y<$dst_h; $y++) {
			$oY = $nY;
			$nY = intval(($y + 1) * $rY+.5);
			$nX = 0;
			for ($x=$src_x; $x<$dst_w; $x++) {
				$r = $g = $b = $a = 0;
				$oX = $nX;
				$nX = intval(($x + 1) * $rX+.5);
				for ($i=$nY; --$i>=$oY;) {
					for ($j=$nX; --$j>=$oX;) {
						$c = ImageColorsForIndex ($src_img, ImageColorAt ($src_img, $j, $i));
						$r += $c['red'];
						$g += $c['green'];
						$b += $c['blue'];
						$a++;
					}
				}
				ImageSetPixel ($dst_img, ($x+$dst_x-$src_x), ($y+$dst_y-$src_y), ImageColorClosest ($dst_img, $r/$a, $g/$a, $b/$a));
			}
		}
		return true;
	}
	else { //very fast!
		$dst_w++; $dst_h++; //->no black border
		return imagecopyresized($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
	}
}

//funkcja wrzucaj�ca plik z $url do $path
function upload_image_from_url ($url='', $path='', $perms=true) {
	global $conf;
	
	if(!$url or !$path) exit;
	
	//perms
	if(!perms_check('images', 'upload') && $perms) {
		plugins('std/unauth/');
		redirect('index.php?module=error&error=auth_error');
		exit();   
	}
	//

	if(substr($url, 0, 7) == 'http://' or substr($url, 0, 6) == 'ftp://' or substr($url, 0, 8) == 'https://')
		$url = $url;
	else
		$url = 'http://'.$url;

	$fext = end($foo = explode(".", $path));
	$url_ext = strtolower(end($foo = explode(".", $url)));

	//checking extensions
	if($fext != $url_ext) {
		redirect('index.php?module=error&error=image_error5');
		exit();
	}

	//uploading
	$return=upload_file_from_url_safe_mode($url, $path);
	//
	
	//resize
	make_image_minature($path, $path, $conf['max_img_width'], $conf['max_img_height'], $perms);
	
	return $return;
}

//wrzuca plik zawarty w $file do $path
function upload_image_form($file='', $path='', $perms=true) {
	global $conf;
	
	if(!$file or !$path) exit;
	
	//perms
	if(!perms_check('images', 'upload') && $perms) {
		plugins('std/unauth/');
		redirect('index.php?module=error&error=auth_error');
		exit();   
	}

	if(is_uploaded_file($file['tmp_name'])) {
		//checking extenstion
		$fext = end($foo = explode('.', $path));
		$ext = strtolower(end($foo = explode('.', $file['name'])));
		if($fext != $ext) {
			redirect('index.php?module=error&error=image_error5');
			exit();
		}
		
		//moving to path
		move_uploaded_file_safe_mode($file['tmp_name'], $path);
		
		//resize
		make_image_minature($path, $path, $conf['max_img_width'], $conf['max_img_height'], $perms);
	}
}

//funkcja tworzaca miniature pliku znajdujacego sie w $path, w postaci md5($path)
//zwraca tablice szer, wys, szer_min, wys_min
function make_image_minature($to='', $from='', $max_width, $max_height, $perms=true) {
	global $conf;
	
	if(!$to or !$from) exit;	
	
	//perms
	if(!perms_check('images', 'upload') && $perms) {
		plugins('std/unauth/');
		redirect('index.php?module=error&error=auth_error');
		exit();   
	}
	
	$fext=end($foo=explode('.', $from));
	$to=str_replace('.'.end($foo=explode('.', $to)), '', $to).'.'.$fext;
	
	list($width, $height, $value, $params) = GetImageSize($from);
	
	if(($width > $max_width) || ($height > $max_height)) {
		$new_width  = $max_width;
		$new_height  = (int)($height*($new_width/$width));
 
		if($new_height > $max_height) {
			$new_height  = $max_height;
			$new_width  = (int)(($width*$new_height)/$height);
		}

		if(($fext == 'jpeg') || ($fext == 'jpg')) {
			$newImage = ImageCreateTrueColor($new_width, $new_height);
			$cpyImage = ImageCreateFromJPEG($from);
			ImageCopyResampled($newImage, $cpyImage, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			ImageJPEG($newImage, $to, 80);
		}
		elseif($fext == 'gif') {
			$newImage = ImageCreateTrueColor($new_width, $new_height);
			$cpyImage = ImageCreateFromGIF($from);
			ImageCopyResampled($newImage, $cpyImage, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			ImageGIF($newImage, $to);
		}
		elseif($fext == 'png') {
			$newImage = ImageCreateTrueColor($new_width, $new_height);
			$cpyImage = ImageCreateFromPNG($from);
			ImageCopyResampled($newImage, $cpyImage, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			ImagePNG($newImage, $to);
		}
		//
	}
	else {
		$new_height = $height;
		$new_width = $width;
		if(eregi("^(gif|jpg|jpeg|png)$", $fext))
			copy_safe_mode($from, $to);
	}

	return array($width, $height, $new_width, $new_height);
}

//funkcja zwraca tablic� informacji o pliku graficznym o id=$id_
function get_image_variables($id_) {
	SQLvalidate($id_);

	$db=new dbquery;
	$db->query("SELECT * FROM $conf[prefix]images WHERE id=$id_") or $db->err(__FILE__, __LINE__);
	$i=$db->fetch_object();

	$images_sort="ORDER by ".$_SESSION['images_sortby'].' '.$_SESSION['images_sort'];
	$db->query("SELECT * FROM $conf[prefix]images WHERE path='$i->path' ".$images_sort) or $db->err(__FILE__, __LINE__);
	$i->back=0;
	$i->next=0;

	while($d=$db->fetch_object()) {
		if($d->id==$id_) {
			$d=$db->fetch_object();
			$i->next=$d->id;
			break;
		}
		$i->back=$d->id;
	}

	return $i;
}

//generating list of dirs for select or images module in admin
function dir_list($dir, $depth, $option) {
	global $conf, $content, $lang, $path_options;

	$dirs = array();

	if($dir=='/')
		$dir='';

	if($d = opendir($conf['images_dir'].$dir)) {
		while($file = readdir($d)) {
			if(($file != ".") && ($file != "..") and !eregi("^\..+", $file)) {
				if(is_dir($conf['images_dir'].$dir.$file))
					$dirs[] = $dir.$file.'/';
			}
		}
	}
	
	if(is_array($dirs))
		sort($dirs);
	for($i = 0; $i < count($dirs); $i++) {
		if($option == 'view_dir')
			$content .= '<tr>
				<td class="row_1" align="left"><img src="'.$GLOBALS['theme_path'].'gfx/blank.gif" width="'.(15*$depth).'" height="10"><img src="admin/gfx/icons/icon_folder.gif" width="16" height="16"> <a href="index.php?module=admin&action=images&cmd=view_dir&amp;dir='.$dirs[$i].'">'.eregi_replace("^$dir/", '', $dirs[$i]).'</a></td>
				<td class="row_1" align="center">'.date("d.m.Y", filemtime($conf['images_dir'].$dirs[$i])).'</td>
				<td class="row_1" align="center"><a href="index.php?module=admin&action=images&cmd=mkdir&amp;dir='.$dirs[$i].'">'.$lang[file_md].'</a>, <a href="index.php?module=admin&action=images&cmd=rmdir&amp;dir='.$dirs[$i].'">'.$lang[file_rm].'</a></td>
				</tr>';
		elseif($option == 'new') {
			$path_options .= '<option value="'.$dirs[$i].'"';
			if($_GET['dir'] == $dirs[$i])
				$path_options .= ' selected';
			$path_options .= '>'.$dirs[$i].'</option>
				';
		}
		else {
			$path_options .= '<option value="'.$dirs[$i].'"';
			if($option == $dirs[$i])
				$path_options .= ' selected';
			$path_options .= '>'.$dirs[$i].'</option>
				';
		}
		dir_list($dirs[$i], ($depth+1), $option);
	}
}
//

//funkcja wyswietlajaca obrazek po nacisnieciu miniatury
function img_gallery() {
	global $conf, $lang, $thm_img;

	if(strpos($_GET['path'], '.')===false && file_exists($conf['images_dir'].$_GET['path']) && $_GET['path']) {
		$dir = opendir($conf['images_dir'].$_GET['path']);
		
		//ustawianie $prev, $img, $next
		$prev='';
		$next='';
		$img='';
		
		while (false !== ($file = readdir($dir))) {
			$fext=explode('.', $file);
			if (is_file($conf['images_dir'].$_GET['path'].$file))
				$files[]=$file;
		}
		
		sort($files);
		
		for($i=0;$i<count($files);$i++) {
			if($_GET['name']==$files[$i] or !$_GET['name']) {
				$img=$files[$i];
				if($files[$i+1])
					$next=$files[$i+1];
				break;
			} else
				$prev=$files[$i];
		}
		
		if($prev)
			$prev='<span class="btn"><a href="index.php?function=img_gallery&path='.urlencode($_GET['path']).'&amp;name='.urlencode($prev).'"><img src="'.$GLOBALS['theme_path'].$GLOBALS['theme_img']['prev'].'" alt="" /></a></span>';
		
		//do linku wy��czaj�cego / w��czaj�cego slideshow
		if($_GET['slideshow']) $ss='';
		else $ss='on';
		
		if($next) {
			$next_url='index.php?function=img_gallery&path='.urlencode($_GET['path']).'&name='.urlencode($next).'&slideshow='.$_GET['slideshow'];
			$next='<span class="btn"><a href="'.$next_url.'"><img src="'.$GLOBALS['theme_path'].$GLOBALS['theme_img']['next'].'" alt="" /></a></span>';
			$slide_show='<span class="btn"><a href="index.php?function=img_gallery&path='.urlencode($_GET['path']).'&name='.urlencode($img).'&amp;slideshow='.$ss.'"><img src="'.$GLOBALS['theme_path'].$GLOBALS['theme_img']['slide_show'].'" alt="" /></a></span>';
		} else {
			$_GET['slidshow']='';
			$next_url='javascript:window.close();';
		}
		
		$img=$conf['images_dir'].$_GET['path'].$img;
	}

	$tpl = new tpl;
	$tpl->create('other/img_gallery.php', array('theme_path'=>$GLOBALS['theme_path'], 'prev'=>$prev, 'next'=>$next, 'next_url'=>$next_url, 'slide_show'=>$slide_show, 'img'=>$img, 'alt'=>$alt));
	$tpl->parse();
}

//funkcja wyswietla losowy obrazek
function random_image($template, $path=NULL) {
	global $conf;

	SQLvalidate($path, 'varchar');

	if($path)
		$sql=" WHERE path LIKE '%$path%'";

	$db=new dbquery;
	$db->query("SELECT * FROM $conf[prefix]images$sql ORDER BY RAND() LIMIT 1") or $db->err(__FILE__, __LINE__);

	$i=$db->fetch_object();

	$img='<img src="'.$conf['images_min_dir'].$i->id.'.'.end($foo = explode('.', $i->name)).'" />';

	$dsc = "desc_$_SESSION[lang_short]";

	if($i->$dsc == '') {
		$dsc = "desc_$conf[language]";
	}

	$desc=$i->$dsc;

	$string=string_template($template, array('img_min'=>$img, 'img'=>$conf['images_dir'].$i->path.$i->name, 'desc'=>$desc));

	echo($string);
}
?>
